﻿@page "/tool"
@using System.Security.Cryptography.X509Certificates
@using System.Security.Cryptography

<PageTitle>Tool</PageTitle>

<MudText Typo="Typo.h3" GutterBottom="true">Tool</MudText>

<div class="d-flex">
    <MudTextField @bind-Value="userName" Label="UserName" Variant="Variant.Text" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.LockPerson" />
    <MudTextField @bind-Value="password" Label="Password" Variant="Variant.Text" InputType="@PasswordInput"
                  Adornment="Adornment.End" AdornmentIcon="@PasswordInputIcon" OnAdornmentClick="ButtonTestclick" AdornmentAriaLabel="Show Password" />
    <MudButton Disabled="@_processing" OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary">
        @if (_processing)
        {
            <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
            <MudText Class="ms-2">Processing</MudText>
        }
        else
        {
            <MudText>login</MudText>
        }
    </MudButton>
</div>


@code {
    private string userName = "likeshan";
    private string password = "Sfqd@20220428";
    private bool _processing = false;

    bool isShow;
    InputType PasswordInput = InputType.Password;
    string PasswordInputIcon = Icons.Material.Filled.VisibilityOff;

    void ButtonTestclick()
    {
        @if (isShow)
        {
            isShow = false;
            PasswordInputIcon = Icons.Material.Filled.VisibilityOff;
            PasswordInput = InputType.Password;
        }
        else
        {
            isShow = true;
            PasswordInputIcon = Icons.Material.Filled.Visibility;
            PasswordInput = InputType.Text;
        }
    }

    async Task ProcessSomething()
    {
        string certificatePath = @"E:\sfqd\cert\李克善\李克善.p12"; // ✅ 使用 .p12 文件
        string certificatePassword = "wXsjm1VN";
        _processing = true;
        string apiUrl = "https://yunwei.beijing.gwhome:34443/authenticate/"; // 目标 API 地址
        try
        {
            // 2. 加载客户端证书
            // 从文件加载 .p12/.pfx 证书
            X509Certificate2 clientCertificate = new X509Certificate2(
                certificatePath,
                certificatePassword,
                X509KeyStorageFlags.MachineKeySet | // 将密钥存储在机器级别
                X509KeyStorageFlags.PersistKeySet   // 持久化密钥（可选）
            );

            // (可选) 验证证书是否包含私钥
            if (!clientCertificate.HasPrivateKey)
            {
                throw new InvalidOperationException("加载的证书不包含私钥，无法用于客户端认证。");
            }

            Console.WriteLine($"已加载证书: {clientCertificate.Subject}");

            // 3. 创建 HttpClientHandler 并附加证书
            var handler = new HttpClientHandler();
            handler.ClientCertificates.Add(clientCertificate); // 将客户端证书添加到处理程序

            // 4. 创建 HttpClient
            using (var httpClient = new HttpClient(handler))
            {
                // (可选) 设置请求头等
                // httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");

                // 5. 发送请求
                Console.WriteLine($"正在调用: {apiUrl}");
                // 构建 Form 数据
                var formData = new MultipartFormDataContent();
                // 添加文本字段
                formData.Add(new StringContent(userName), "username");
                formData.Add(new StringContent(password), "password");
                HttpResponseMessage response = await httpClient.PostAsync(apiUrl, formData);

                // 6. 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("请求成功！");
                    Console.WriteLine($"状态码: {response.StatusCode}");
                    Console.WriteLine($"响应内容: {responseBody}");
                }
                else
                {
                    Console.WriteLine($"请求失败，状态码: {response.StatusCode}");
                    Console.WriteLine($"原因: {response.ReasonPhrase}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
            if (ex is CryptographicException cryptoEx)
            {
                Console.WriteLine($"加密错误详情: {cryptoEx.Message}");
                // 通常是密码错误或证书格式问题
            }
        }
        finally
        {
            // (可选) 显式清理证书对象（using 语句通常已处理）
            // clientCertificate?.Dispose();
        }
        _processing = false;
    }
}